package com.lcb.jvm;


import java.io.FileInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
* @Author: 刘长柏
* @Date: 2021-01-03
* @Description:  自定义类加载器
*/
public class MyClassLoaderTest {

    static class  MyClassLoader extends  ClassLoader{

        private String classPath;

        public MyClassLoader(String classPath){
            this.classPath=classPath;
        }

        public byte[] loadByte(String name) throws Exception {
            name=name.replaceAll("\\.","/");
            FileInputStream fis=new FileInputStream(classPath+"/"+name+".class");
            int len = fis.available();
            byte[] data=new byte[len];
            fis.read(data);
            fis.close();
            return data;
        }

        @Override
        protected Class<?> findClass(String name) throws ClassNotFoundException {
            try {
                byte[] data =loadByte(name);
                return defineClass(name,data,0,data.length);
            } catch (Exception e) {
                e.printStackTrace();
                throw new ClassCastException();
            }
        }
    }

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        ///初始化自定义加载器,其中会把自定义类加载器设置为应用程序类加载器AppClassLoader
        MyClassLoader classLoader=new MyClassLoader("D:/test");
        Class clazz = classLoader.loadClass("com.lcb.jvm.User1");
        Object o = clazz.newInstance();
        Method sout = clazz.getDeclaredMethod("getAge", null);
        sout.invoke(o,null);

        System.out.println(clazz.getClassLoader().getClass().getName());

    }
}
